package com.hudson.example.hudsonmq;

import com.hudson.codec.domain.Message;
import com.hudson.core.concurrent.CallBack;
import com.hudsonmq.spring.impl.HudsonMQTemplate;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author: 渔小鲤
 * @DateTime: 2025/8/17 2:36
 **/
@Component
public class HudsonMQSendTest implements ApplicationRunner {


    private static final Logger log = LoggerFactory.getLogger(HudsonMQSendTest.class);
    @Resource
    private HudsonMQTemplate hudsonMQTemplate;

    @Override
    public void run(ApplicationArguments args) throws Exception {

        ExecutorService executorService = Executors.newFixedThreadPool(128);
        AtomicInteger integer = new AtomicInteger();

        for (int i = 0; i < 20; i++) {
            executorService.submit(() -> {
                while (true) {
                    try {
                        int index = integer.getAndIncrement();
                        Message message = Message.builder()
                                .topic("test")
                                .body(("第" + index + "条消息-新topic").getBytes(StandardCharsets.UTF_8))
                                .tags("tag1")
                                .build();
                        hudsonMQTemplate.send(message, new CallBack() {
                            @Override
                            public void onSuccess() {
                                log.debug("異步發送成功");
                            }

                            @Override
                            public void onFail(Throwable e) {

                            }
                        });
//                        hudsonMQTemplate.syncSend(new SendMessage("test", ("第" + index + "条消息-新topic").getBytes(StandardCharsets.UTF_8), new SendCallBack() {
//                            @Override
//                            public void onSuccess() {
//                                log.debug("異步發送成功");
//                            }
//
//                            @Override
//                            public void onFail(Throwable e) {
//
//                            }
//                        }));
                        Thread.sleep(100);
                    } catch (Exception e) {
                        log.debug(e.getMessage());
                        Thread.sleep(2000);
                    }
                }

            });
        }
    }
}
